import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';
import moment from 'moment';

import { addTab, timeLimit } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import PageHeader from '@/components/PageHeader';

import {
  Card,
  Row,
  Col,
  Select,
  DatePicker,
  Button,
  Table,
  Tooltip,
  message,
} from 'antd';

import PrintElemInfo from './components/PrintElem';
import { tookDeposit } from '../../../../../config/Apis';

import '@ant-design/compatible/assets/index.css';

const { RangePicker } = DatePicker;
const { Option } = Select;

const { pathname } = window.location;

interface TableProps extends FormComponentProps {
  dispatch: Dispatch;
  location: { query: any };
  tookManagementReceipt: any;
  INITINFO: any;
  loading: boolean;
  printLoading: boolean;
  exportLoading: boolean;
}

interface TableState {
  formValues: any;
  current: number;
  pageSize: number;
  rowId:number;
}

@connect(({ tookManagementReceipt, common: { INITINFO }, loading }: any) => ({
  tookManagementReceipt,
  INITINFO,
  loading: loading.effects['tookManagementReceipt/fetch'],
  printLoading: loading.effects['tookManagementReceipt/printOutbox'],
  exportLoading: loading.effects['tookManagementReceipt/export'],
}))
class ReceiptElem extends React.Component<TableProps, TableState> {
  columns: any = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 100,
      render: (text: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '运单号',
      dataIndex: 'expCode',
      width: 120,
      render: (text: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text || '--'}</div>
        </Tooltip>
      ),
    },
    {
      title: '快递公司',
      dataIndex: 'expressName',
      width: 120,
      render: (text: any, record: any) => (
        <Tooltip title={`${text}/${record.senderPhone}`}>
          <div className="wordOmit">
            <span>
              {text}/{record.senderPhone}
            </span>
          </div>
        </Tooltip>
      ),
    },
    {
      title: '目的地',
      dataIndex: 'destination',
      width: 160,
      render: (text: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text || '--'}</div>
        </Tooltip>
      ),
    },
    {
      title: '包裹重量',
      dataIndex: 'weight',
      width: 100,
      render: (val: string) => `${val}KG`,
    },
    {
      title: '快递收入',
      dataIndex: 'realFee',
      width: 100,
      render: (val: string) => `${val}元` || '--',
    },
    {
      title: '保价费',
      dataIndex: 'insureFee',
      width: 80,
      render: (val: string) => `${val}元` || '--',
    },
    {
      title: '包装费',
      dataIndex: 'packageFee',
      width: 80,
      render: (val: string) => `${val}元` || '--',
    },
    {
      title: '支付快递公司',
      dataIndex: 'painExpress',
      width: 120,
      render: (val: string) => `${val}元` || '--',
    },
    {
      title: '付款方式',
      dataIndex: 'settleDesc',
      width: 100,
    },
    {
      title: '出库时间',
      dataIndex: 'outTime',
      width: 200,
      render: (val: string) => val || '--',
    },
    {
      title: '揽件人',
      dataIndex: 'courierName',
      width: 100,
      render: (val: string) => val || '--',
    },
    {
      title: '出库人',
      dataIndex: 'sentName',
      width: 100,
      render: (val: string) => val || '--',
    },
    {
      title: '状态',
      dataIndex: 'statusName',
      width: 80,
    },
  ];

  state: TableState = {
    formValues: {},
    current: 1,
    pageSize: 20,
    rowId: 0,
  };

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { pageIndex, pageSize, ...formValues } = query;
    return {
      ...state,
      formValues,
      current: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (props.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.fetchExpressList();
    this.fetchLogisList();
    this.fetchSendingCount();
    this.fetchSendingStatus();
    this.setFieldsValue();
    this.fetchDataListInfo();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { formValues, current, pageSize } = this.state;
    if (
      !_.isEqual(formValues, prevState.formValues)
      || current !== prevState.current
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataListInfo();
      this.fetchSendingCount();
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'tookManagementReceipt/clear',
    });
  }

  // 设置表单值
  setFieldsValue = () => {
    const { formValues }: any = this.state;
    const { form } = this.props;

    const { startTime, endTime, ...values } = formValues;

    if (startTime) {
      values.startEndTime = [moment(startTime), endTime && moment(endTime)];
    } else {
      values.startEndTime = [
        moment(
          moment()
            .subtract(7, 'days')
            .format('YYYY/MM/DD'),
        ),
      ];
    }

    form.setFieldsValue(values);
  };

  // 获取数据
  fetchDataListInfo = () => {
    const { dispatch } = this.props;
    const params = this.getQueryParams();
    if (params.logisId && params.expressId && params.startTime) {
      dispatch({
        type: 'tookManagementReceipt/fetch',
        payload: this.getQueryParams(),
      });
    }
  };

  // 获取查询参数
  getQueryParams = () => {
    const { formValues, current, pageSize } = this.state;

    const params: any = {
      ...formValues,
      pageIndex: current,
      pageSize,
    };
    if (!params.startTime) {
      params.startTime = moment()
        .subtract(7, 'days')
        .format('YYYY-MM-DD 00:00:00');
    }

    return params;
  };

  /**
   * 获取快递公司列表
   */
  fetchExpressList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchExpressList',
    });
  };

  /**
   * 获取物流中心列表
   */
  fetchLogisList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchLogisList',
    });
  };

  /** 获取信息统计 */
  fetchSendingCount = (type?: number) => {
    const { dispatch } = this.props;
    const { pageIndex, pageSize, ...query } = this.getQueryParams();
    if (type) query.type = type;
    dispatch({
      type: 'tookManagementReceipt/sendingCount',
      payload: query,
    });
  };

  /**
   * 获取订单状态
   */
  fetchSendingStatus = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tookManagementReceipt/sendingStatus',
    });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const {
      dispatch,
      form: { validateFields },
    } = this.props;
    validateFields((errors, values) => {
      if (!errors) {
        const { startEndTime, ...params } = values;
        if (!params.logisId) message.error('请选择物流中心');
        else if (!params.expressId) message.error('请选择快递公司');
        else if (!startEndTime || !startEndTime.length) message.error('请选择日期');
        else {
          const query = {
            ...params,
            pageIndex: 1,
            pageSize: 20,
          };

          query.startTime = startEndTime[0]
            ? moment(startEndTime[0]).format('YYYY-MM-DD HH:mm:ss')
            : moment()
              .subtract(7, 'days')
              .format('YYYY-MM-DD 00:00:00');

          query.endTime = startEndTime[1] && moment(startEndTime[1]).format('YYYY-MM-DD HH:mm:ss');

          addTab(dispatch, {
            name: '打印出库交接单',
            url: `${pathname}?${qs.stringify(query)}`,
            isTopMenu: true,
          });
        }
      }
    });
  };

  handleReset = () => {
    const {
      dispatch,
      form: { resetFields },
    } = this.props;
    resetFields();
    dispatch({
      type: 'tookManagementReceipt/clear',
    });
    addTab(dispatch, {
      name: '打印出库交接单',
      url: pathname,
      isTopMenu: true,
    });
  };

  /** 翻页 */
  onSelectChange = (current: number, pageSize: number) => {
    const { formValues } = this.state;
    const { dispatch } = this.props;
    const query = {
      ...formValues,
      pageIndex: current,
      pageSize,
    };

    addTab(dispatch, {
      name: '打印出库交接单',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  getSearchFormValues = () => {
    const {
      form: { getFieldValue },
    } = this.props;
    const logisId = getFieldValue('logisId');
    const expressId = getFieldValue('expressId');
    const status = getFieldValue('status');
    const date = getFieldValue('startEndTime');

    if (!logisId) {
      message.error('请选择物流中心');
      return null;
    }

    if (!expressId) {
      message.error('请选择快递公司');
      return null;
    }

    if (!date || !date.length) {
      message.error('请选择时间');
      return null;
    }
    return {
      logisId,
      expressId,
      status,
      startTime: moment(date[0]).format('YYYY-MM-DD'),
      endTime: moment(date[1]).format('YYYY-MM-DD'),
    };
  };

  /** 打印出库交接单 */
  handlePrintOutboundOrder = () => {
    const { current, pageSize } = this.state;
    const {
      dispatch,
      INITINFO: { logisList, expressList },
    } = this.props;
    const params: any = this.getSearchFormValues();
    if (params) {
      params.pageIndex = current;
      params.pageSize = pageSize;
      params.logisName = logisList.find((item: any) => item.id === Number(params.logisId)).name;
      params.expressName = expressList.find(
        (item: any) => item.id === Number(params.expressId),
      ).name;
      dispatch({
        type: 'tookManagementReceipt/printOutbox',
        payload: params,
      });
    }
  };

  /** 导出交接单 */
  handleExportOutboundOrder = () => {
    const { current, pageSize } = this.state;
    const params: any = this.getSearchFormValues();
    if (params) {
      params.pageIndex = current;
      params.pageSize = pageSize;

      window.location.href = `${tookDeposit.sending_exportExcel}?${qs.stringify(params)}`;
    }
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  renderSearchFormElem() {
    const {
      form: { getFieldDecorator },
      INITINFO: { expressList, logisList },
    } = this.props;
    return (
      <Form className="tableListForm" onSubmit={this.handleSearch}>
        <Row gutter={12}>
          <Col md={12} sm={24}>
            <Form.Item label="　　日期" colon={false}>
              {getFieldDecorator('startEndTime')(
                <RangePicker
                  placeholder={['开始时间', '截止时间']}
                  style={{ width: '100%' }}
                  disabledDate={timeLimit}
                  ranges={{
                    今天: [moment().startOf('day'), moment().endOf('day')],
                    本周: [moment().startOf('week'), moment().endOf('week')],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                    上月: [
                      moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                      moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                    ],
                  }}
                />,
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <Form.Item label="物流中心" colon={false}>
              {getFieldDecorator('logisId')(
                <Select
                  showSearch
                  allowClear
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => (
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  )}
                >
                  {logisList.map((item: any) => (
                    <Option value={String(item.id)} key={item.id}>
                      {item.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </Form.Item>
          </Col>
          <Col md={6} sm={24}>
            <Form.Item label="快递公司" colon={false}>
              {getFieldDecorator('expressId')(
                <Select
                  showSearch
                  allowClear
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => (
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  )}
                >
                  {expressList.map((item: any) => (
                    <Option value={String(item.id)} key={item.id}>
                      {item.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </Form.Item>
          </Col>
          <Col md={6} sm={24}>
            <Form.Item label="订单状态" colon={false}>
              {getFieldDecorator('status', { initialValue: '5' })(
                <Select placeholder="请选择">
                  <Option value="5">已出库</Option>
                </Select>,
              )}
            </Form.Item>
          </Col>
          <Col md={6} sm={24}>
            <div className="flexFeView">
              <Button
                type="primary"
                htmlType="submit"
                className="smallButton"
              >
                查询
              </Button>
              <Button
                type="primary"
                className="addButton smallButton marginL16"
                onClick={this.handleReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const { current, pageSize } = this.state;
    const {
      loading,
      printLoading,
      exportLoading,
      tookManagementReceipt: { dataInfo, countInfo },
    } = this.props;

    const pagination: any = dataInfo
      ? {
        total: dataInfo ? dataInfo.count : 0,
        pageSize,
        current: current || 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    return (
      <>
        <PageHeader />
        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>
        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              loading={printLoading}
              className="marginR16"
              onClick={this.handlePrintOutboundOrder}
            >
              打印出库交接单
            </Button>
            <Button
              type="primary"
              size="small"
              loading={exportLoading}
              className="marginR16"
              onClick={this.handleExportOutboundOrder}
            >
              导出交接单
            </Button>
            <span style={{ float: 'right', color: 'red' }}>未出库订单：{countInfo.paid || 0}</span>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataInfo.list || []}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1600 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
        <PrintElemInfo />
      </>
    );
  }
}

export default Form.create<TableProps>()(ReceiptElem);
